clear
capture restore
set scheme cleanplots, perm

* SET DIRECTORIES
global home "..."

global data "$home/Data/"
global output "$home/Output/"

cd $home


*SET CONTROL VARIABLES
local firm_controls "log_salesg_real_1lag_std size_assets_1lag_std liquidity_1lag_std pcmq_1lag_std recpay2yq_1lag_std d2aq_1lag_std ln_market_cap_q_1lag_std tobins_q_1lag_std lev_d2c_1lag_std i.sector i.fqtr"

local agg_controls "lngdp inflation unemp nasdaq fedfunds"

*************
***Options***
*************
*Set ivol measure to use as baseline
local matur m1545
*Set mp shock to use as baseline
local mps ff4_d

* Set the LP details ========================================================================
*# periods to compute the responses foreach
local hor = 30
*# lags of "endogenous" variables 
local lagy = 4 
*# lags of "shock"
local lage = 0 

********************************************************************************
********************************************************************************
********************************************************************************
*Read-in ivol data (contains all trading days for Compustat firms)
use "${data}Compustat_Quarterly_Final", clear

local n = 20

*Set panel data
xtset firmid ts_qtr

*Flag sample for those in at least n quarters
bysort gvkey pre_crisis: egen obs_num_temp = count(gvkey) if pre_crisis
bysort gvkey: egen obs_num = max(obs_num_temp)

*Flag outliers (bottom/top 0.5%) for investment
_pctile investment_intensive if pre_crisis, p(.5 99.5)
gen 	investment_outlier = (investment_intensive<r(r1)|investment_intensive>r(r2))

gen sample_period=(pre_crisis==1)

gen in_sample = (obs_num>=`n' & !missing(obs_num) & investment_outlier==0 & sample_period)

keep if in_sample

egen date_tag=tag(ts_qtr)

********************************************************************************
*TIME-SERIES FIGURE OF IVOL WITH 20TH AND 80TH PERCENTILES
********************************************************************************
bysort ts_qtr: egen p50_ivol_`matur' = pctile(ivol_`matur'), p(50)
bysort ts_qtr: egen p30_ivol_`matur' = pctile(ivol_`matur'), p(30)
bysort ts_qtr: egen p70_ivol_`matur' = pctile(ivol_`matur'), p(70)

drop if missing(p50_ivol_`matur')
	
twoway (rarea p30_ivol_`matur' p70_ivol_`matur' ts_qtr, fcolor(gs14) lcolor(gs14) lw(none) lpattern(solid)) (line p50_ivol_`matur' ts_qtr, lcolor(black) lpattern(solid) lwidth(thick)) (line vix_q ts_qtr, lcolor(blue) lpattern(dash) lwidth(thick) yaxis(2)) if date_tag, ytitle(Implied Volatility, size(medlarge)) xtitle(Date, size(medlarge)) ylab(,nogrid labsize(medlarge)) xlabel(144 160 176 192, nogrid format(%tqCCYY) labsize(medlarge)) legend(off)	ylabel(,nogrid labsize(medlarge) axis(2)) ytitle(VIX, size(medlarge) axis(2))
graph export "${output}figureA1.pdf", replace
	
	